# collections 模块用于列表、字典、队列等的集合类和方法 
# defaultdict用于查询字典中不存在的key时，不抛出异常而是返回一个默认值
# pathlib模块用于进行路径拼接转换等操作
from pathlib import Path
from collections import defaultdict


import glob


def dealStatFile(input_dir,fq_dir,_samples,_lane):
  _samplesDir = {}
  _rawsamplesDir = {}
  path = Path(input_dir)
  _bclDir = path.absolute()
  _runid = _bclDir.name
  statfiles = glob.glob(f'{_bclDir}/*/SequenceStat.txt')
  # statifles: '/data/share/S200040704/L01/SequenceStat.txt'
  ''' SequenceStat.txt 格式
        #Sequence        Barcode             Count         Percentage(%)
        TCACGATACA       Barcode103        48897390        6.927668
        ACGGTAATGG       Barcode101        45592658        6.459460
        ...
  '''
  '''defaultdict(int)：初始化为 0
    defaultdict(float)：初始化为 0.0
    defaultdict(str)：初始化为 " '''
  lanestat = defaultdict(lambda: defaultdict(int))
  undecoded, allcount = defaultdict(int), defaultdict(int)
  for f in statfiles:
    # 获取SequenceStat.txt上一级文件夹名字（样本名）
    laneid = f.split('/')[-2]
    # 处理SequenceStat文件
    with open(f) as stats:
      stats.readline()
      for l in stats:
        x = l.split('\t')
        # allcount:{L01:sum(count),L02:sum(count)}
        # 统计每条lane对应的总Count数
        allcount[laneid] += int(x[2].strip())
        z = x[1].strip()
        # 若第二列包含barcode字符，则将lane的前缀去掉 只保留编号并将count数存入字典 否则计入undecode
        # lanestat:{L01:{{(barcode)00:count},{(barcode)01:count}...}}(bcl中每个barcode的count数)
        # 统计barcode数目
        if z.find('Barcode') > -1 or z.find('barcode')>-1:
          lanestat[laneid][z.strip('Barcode').strip('barcode')] += int(x[2].strip())
        else:
          undecoded[laneid] += int(x[2].strip())
        # return (allcount,lanestat,undecoded)
  with open(f'{fq_dir}/SequenceStat.txt','w') as SequenceStat:
    SequenceStat.write('Barcode\tCount\n')
    # 把undecode的数据写入sequencestat文件
    for k,v in undecoded.items():
      SequenceStat.write(f'undecoded_{k}\t{v}\n')
    samplecount = defaultdict(int)
    # _samples:{I7_Index_ID:sampleId}
    #_lane:{I7_Index_ID:laneIndex}（多条lane以&连接）
    for i, e in _samples.items():
      _samplesDir[e] = Path(f'./{_runid}/{e}').absolute()
      _rawsamplesDir[e] = fq_dir / Path(f'{e}.fq.gz')
      # 若对应样本的文件夹不存在则创建
      # if not _samplesDir[e].exists():
      #   _samplesDir[e].mkdir()
      lane = _lane[i].split('&')
      # 如果每个I7Index只对应一条lane 将
      if len(lane) == 1:
        x = lane[0][1]
        z = f'L0{x}'
        # 样本数为将该条lane的不同种类barcode的count数相加
        
        samplecount[z] += lanestat[z][i]
        SequenceStat.write(f'Barcode{i}\t{lanestat[z][i]}\n')
        # out.write(f'cat {_bclDir}/L0{x}/{_runid}_L0{x}_{i}.fq.gz > {_L01Dir}/{e}_{i}.fq.gz\n')
      else:
        sumcount = 0
        # 若为多条lane 样本数为每条lane的不同种类barcode的count数相加
        for n, j in enumerate(lane):
            z = f'L0{j[1]}'
            sumcount += lanestat[z][i]
            samplecount[z] += lanestat[z][i]
        SequenceStat.write(f'Barcode{i}\t{sumcount}\n')
        # fqs = ' '.join([f'{_bclDir}/L0{j[1]}/{_runid}_L0{j[1]}_{i}.fq.gz' for n, j in enumerate(lane)])
        # out.write(f'cat {fqs} > {_L01Dir}/{e}_{i}.fq.gz\n')
      # subprocess.run(f'ln -s {str(_outdir)}/L01/{e}_{i}.fq.gz {str(_rawsamplesDir[e])}', shell=True)
    left = defaultdict(int)
    totalReads = 0
    # otherIndex：总数减去该条lane的样本数和undecode数目
    # totalreads：所有lane的count数总和
    for k,v in allcount.items():
      left[k] = allcount[k] - samplecount[k] - undecoded[k]
      SequenceStat.write(f'otherindex_{k}\t{left[k]}\n')
      totalReads += allcount[k]
    SequenceStat.write(f'TotalReads\t{totalReads}\n')
    return (_samplesDir,_rawsamplesDir)
    #skip all BY(embryo_cnv) sameple
if __name__ == "__main__":
  print('as')
  # dealStatFile("/data/share/S200040707/","./","/home/zhengzhiqiang/0528.S200040707.csv")